package pl.edu.mimuw.irs.core.util.persistence;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

import pl.edu.mimuw.irs.rcp.util.Logger;
import pl.edu.mimuw.irs.rcp.util.MessageCode;

public class IRSWorkflowPersistence implements IPersistenceManager {

	// *** Attributes

	// *** Methods

	public IRSWorkflowPersistence() {

	}

	public Object loadFromFile(String file) throws Exception {
		return loadFromStream(new FileInputStream(new File(file)));
	}

	public Object loadFromStream(InputStream stream) throws IOException, ClassNotFoundException {
		Object object = null;
		ObjectInputStream objectStream = null;
		
		objectStream = new ObjectInputStream(stream);
		object = objectStream.readObject();
		objectStream.close();
		
		return object;
	}

	public void writeToFile(Object object, String file) throws Exception {
		writeToStream(object, new FileOutputStream(new File(file)));
	}

	public void writeToStream(Object object, OutputStream stream) throws IOException {
		
		ObjectOutputStream objectStream = null;
		
		objectStream = new ObjectOutputStream(stream);
		objectStream.writeObject(object);
		objectStream.close();
		
	}

	@Override
	public InputStream objectAsInputStream(Object object) throws Exception {

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		
		try {
			writeToStream(object, baos);
		} catch (Exception ex) {
			Logger.handle(MessageCode.WORKFLOW_SAVE_SERIALIZE_PROBLEM, ex);
			return null;
		}
		
		InputStream source = new ByteArrayInputStream(baos.toByteArray());
		return source;
	}
}
